package com.itheima.easy.handler.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.itheima.easy.client.wechat.Config;
import com.itheima.easy.client.wechat.Factory;
import com.itheima.easy.client.wechat.response.CloseResponse;
import com.itheima.easy.client.wechat.response.QueryResponse;
import com.itheima.easy.client.wechat.response.RefundResponse;
import com.itheima.easy.config.WechatPayConfig;
import com.itheima.easy.constant.SuperConstant;
import com.itheima.easy.constant.TradingConstant;
import com.itheima.easy.enums.TradingEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.handler.BeforePayHandler;
import com.itheima.easy.handler.CommonPayHandler;
import com.itheima.easy.mq.MqMessage;
import com.itheima.easy.pojo.RefundRecord;
import com.itheima.easy.pojo.Trading;
import com.itheima.easy.service.IRefundRecordService;
import com.itheima.easy.service.ITradingService;
import com.itheima.easy.utils.BeanConv;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.utils.ResponseChecker;
import com.itheima.easy.vo.RefundRecordVo;
import com.itheima.easy.vo.TradingVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * @ClassName BasicPayHandlerImpl.java
 * @Description 微信交易基础类
 */
@Service
@Slf4j
public class WechatCommonPayHandler implements CommonPayHandler {

    @Autowired
    ITradingService tradingService;

    @Autowired
    IRefundRecordService refundRecordService;

    @Autowired
    IdentifierGenerator identifierGenerator;

    @Autowired
    BeforePayHandler beforePayHandler;

    @Autowired
    WechatPayConfig wechatPayConfig;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public TradingVo queryTrading(TradingVo tradingVo) {
        //1、查询前置处理：检测交易单参数
        Boolean flag = beforePayHandler.checkQueryTrading(tradingVo);
        if (!flag){
            throw new ProjectException(TradingEnum.CHECK_TRADING_FAIL);
        }
        Trading tradingHandler = tradingService.findTradByTradingOrderNo(tradingVo.getTradingOrderNo());
        //2、获得微信客户端
        Config config = wechatPayConfig.config(tradingVo.getEnterpriseId());
        //3、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradingEnum.CONFIG_ERROR);
        }
        //4、指定配置文件
        Factory factory = new Factory();
        factory.setOptions(config);
        //5、调用接口
        try {
            QueryResponse queryResponse = factory.Common()
                .query(String.valueOf(tradingVo.getTradingOrderNo()));
            //6、判断响应是否成功
            boolean success = ResponseChecker.success(queryResponse);
            //7、响应成功，分析交易状态
            if (success&&!EmptyUtil.isNullOrEmpty(queryResponse.getTradeState())){
                //SUCCESS：支付成功,REFUND：转入退款,NOTPAY：未支付,CLOSED：已关闭,REVOKED：已撤销（仅付款码支付会返回）
                //USERPAYING：用户支付中（仅付款码支付会返回）,PAYERROR：支付失败（仅付款码支付会返回）
                switch (queryResponse.getTradeState()){
                    case TradingConstant.WECHAT_TRADE_CLOSED:
                        tradingHandler.setTradingState(TradingConstant.TRADE_CLOSED);break;
                    case TradingConstant.WECHAT_TRADE_REVOKED:
                        tradingHandler.setTradingState(TradingConstant.TRADE_CLOSED);break;
                    case TradingConstant.WECHAT_TRADE_SUCCESS:
                        tradingHandler.setTradingState(TradingConstant.TRADE_SUCCESS);break;
                    case TradingConstant.WECHAT_TRADE_REFUND:
                        tradingHandler.setTradingState(TradingConstant.TRADE_SUCCESS);break;
                    default:
                        flag = false;break;
                }
                //8.1、修改交易单状态
                if (flag){
                    tradingHandler.setResultCode(queryResponse.getTradeState());
                    tradingHandler.setResultMsg(queryResponse.getTradeStateDesc());
                    tradingHandler.setResultJson(JSONObject.toJSONString(queryResponse));
                    tradingService.updateById(tradingHandler);

                    //8.2 发送消息到MQ
                    Long messageId = (Long) identifierGenerator.nextId(tradingHandler);
                    MqMessage mqMessage = MqMessage.builder()
                            .id(messageId)
                            .title("trade-message")
                            .content(JSONObject.toJSONString(tradingHandler))
                            .messageType("trade-project-sync")
                            .produceTime(Timestamp.valueOf(LocalDateTime.now()))
                            .sender("system")
                            .build();

                    /**
                     * trade-exchange : 交换机的名称
                     * enterpriseId ： 企业id，对应的值为渠道表中的enterprise_id字段的值。
                     *                 每个业务系统都有自己的队列，通过路由key将消息路由到自己的队列
                     *                 此处的路由key就是enterpriseId的值
                     */
                    rabbitTemplate.convertAndSend("trade-exchange",tradingVo.getEnterpriseId().toString(), JSON.toJSONString(mqMessage));

                    return BeanConv.toBean(tradingHandler,TradingVo.class);
                }else {
                    log.info("查询微信交易单：{},结果：{}", tradingVo.getTradingOrderNo(),queryResponse.getTradeState());
                }
            }else {
                throw new RuntimeException("查询微信统一下单失败！");
            }
        } catch (Exception e) {
            log.warn("查询微信统一下单失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new RuntimeException("查询微信统一下单失败！");
        }
        return tradingVo;
    }

    @Override
    public TradingVo refundTrading(TradingVo tradingVo) {
        //1、生成退款请求编号
        tradingVo.setOutRequestNo(String.valueOf(identifierGenerator.nextId(tradingVo)));
        Trading tradingHandler = tradingService.findTradByTradingOrderNo(tradingVo.getTradingOrderNo());
        tradingVo.setTradingAmount(tradingHandler.getTradingAmount());
        //2、退款前置处理：检测交易单参数
        Boolean flag = beforePayHandler.checkRefundTrading(tradingVo);
        if (!flag){
            throw new ProjectException(TradingEnum.TRAD_REFUND_FAIL);
        }
        //3、退款前置处理：退款幂等性校验
        beforePayHandler.idempotentRefundTrading(tradingVo);
        //4、获得微信客户端
        Config config = wechatPayConfig.config(tradingVo.getEnterpriseId());
        //5、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradingEnum.CONFIG_ERROR);
        }
        //6、指定配置文件
        Factory factory = new Factory();
        factory.setOptions(config);
        //7、调用接口
        try {
            RefundResponse refundResponse = factory.Common().refund(
                    String.valueOf(tradingVo.getTradingOrderNo()),
                    String.valueOf(tradingVo.getOperTionRefund()),
                    tradingVo.getOutRequestNo(),String.valueOf(tradingVo.getTradingAmount()));
            boolean success = ResponseChecker.success(refundResponse);
            if (success&&String.valueOf(tradingVo.getTradingOrderNo()).equals(refundResponse.getOutTradeNo())){
                //8、指定此交易单是否有退款：YES
                tradingHandler.setIsRefund(SuperConstant.YES);
                tradingHandler.setRefund(tradingVo.getRefund().add(tradingVo.getOperTionRefund()));
                Trading trading = BeanConv.toBean(tradingVo, Trading.class);
                tradingService.updateById(trading);
                //6、保存退款单信息
                RefundRecord refundRecord = RefundRecord.builder()
                    .enterpriseId(tradingHandler.getEnterpriseId())
                    .storeId(tradingHandler.getStoreId())
                    .refundNo(tradingVo.getOutRequestNo())
                    .refundAmount(tradingVo.getOperTionRefund())
                    .refundCode(refundResponse.getCode())
                    .refundMsg(refundResponse.getMessage())
                    .productOrderNo(tradingHandler.getProductOrderNo())
                    .tradingChannel(tradingHandler.getTradingChannel())
                    .tradingOrderNo(tradingHandler.getTradingOrderNo())
                    .memo("退款："+tradingHandler.getMemo())
                    .build();
                switch (refundResponse.getStatus()){
                    case TradingConstant.WECHAT_REFUND_SUCCESS:
                        refundRecord.setRefundStatus(TradingConstant.REFUND_STATUS_SUCCESS);break;
                    case TradingConstant.WECHAT_REFUND_CLOSED:
                        refundRecord.setRefundStatus(TradingConstant.REFUND_STATUS_CLOSED);break;
                    case TradingConstant.WECHAT_REFUND_PROCESSING:
                        refundRecord.setRefundStatus(TradingConstant.REFUND_STATUS_SENDING);break;
                    default:
                        refundRecord.setRefundStatus(TradingConstant.REFUND_STATUS_FAIL);break;
                }
                refundRecordService.save(refundRecord);
            }else {
                log.error("网关：微信统一下单退款失败：{},结果：{}", tradingVo.getTradingOrderNo(),
                        JSONObject.toJSONString(refundResponse));
                throw new RuntimeException("网关：微信统一下单退款失败!");
            }
        } catch (Exception e) {
            log.error("微信统一下单退款失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradingEnum.TRAD_REFUND_FAIL);
        }
        return BeanConv.toBean(tradingHandler,TradingVo.class);
    }

    @Override
    public RefundRecordVo queryRefundTrading(RefundRecordVo refundRecordVo) {
        //1、退款前置处理：检测退款单参数
        Boolean flag = beforePayHandler.checkQueryRefundTrading(refundRecordVo);
        if (!flag){
            throw new ProjectException(TradingEnum.TRAD_QUERY_REFUND_FAIL);
        }
        RefundRecord refundRecordHandler = refundRecordService.findRefundRecordByRefundNo(refundRecordVo.getRefundNo());
        //2、获得微信客户端
        Config config = wechatPayConfig.config(refundRecordVo.getEnterpriseId());
        //3、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradingEnum.CONFIG_ERROR);
        }
        //4、指定配置文件
        Factory factory = new Factory();
        factory.setOptions(config);
        try {
            RefundResponse refundResponse = factory.Common().queryRefund(refundRecordVo.getRefundNo());
            //5、判断响应是否成功
            boolean success = ResponseChecker.success(refundResponse);
            //6、查询出的退款状态
            if (success&&TradingConstant.WECHAT_REFUND_SUCCESS.equals(refundResponse.getStatus())){
                refundRecordHandler.setRefundStatus(TradingConstant.REFUND_STATUS_SUCCESS);
                refundRecordHandler.setRefundCode(refundResponse.getCode());
                refundRecordHandler.setRefundMsg(refundResponse.getMessage());
                refundRecordService.updateById(BeanConv.toBean(refundRecordHandler,RefundRecord.class));
            }else {
                log.error("网关：查询微信统一下单退款失败：{},结果：{}", refundRecordVo.getTradingOrderNo(),
                        JSONObject.toJSONString(refundResponse));
                throw new RuntimeException("网关：查询微信统一下单退款失败！");
            }
        } catch (Exception e) {
            log.warn("查询微信统一下单退款失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new RuntimeException("查询微信统一下单退款失败！");
        }
        return refundRecordVo;
    }

    @Override
    public TradingVo closeTrading(TradingVo tradingVo) {
        //1、退款前置处理：检测关闭参数tradingVo
        Boolean flag = beforePayHandler.checkCloseTrading(tradingVo);
        if (!flag){
            throw new ProjectException(TradingEnum.TRAD_CLOSE_FAIL);
        }
        Trading tradingHandler = tradingService.findTradByTradingOrderNo(tradingVo.getTradingOrderNo());
        //2、获得微信客户端
        Config config = wechatPayConfig.config(tradingVo.getEnterpriseId());
        //3、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradingEnum.CONFIG_ERROR);
        }
        //4、使用配置
        Factory factory = new Factory();
        factory.setOptions(config);
        try {
            //5、调用三方API关闭订单
            CloseResponse closeResponse = factory.Common()
                    .close(String.valueOf(tradingVo.getTradingOrderNo()));
            //6、关闭订单受理情况
            boolean success = ResponseChecker.success(closeResponse);
            if (success){
                tradingHandler.setTradingState(TradingConstant.TRADE_CLOSED);
                tradingService.updateById(tradingHandler);
                return BeanConv.toBean(tradingHandler,TradingVo.class);
            }else {
                log.error("网关：微信关闭订单失败：{},结果：{}", tradingVo.getTradingOrderNo(),
                        JSONObject.toJSONString(closeResponse));
                throw  new RuntimeException("网关：微信关闭订单失败!");
            }
        } catch (Exception e) {
            log.warn("微信关闭订单失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw  new ProjectException(TradingEnum.TRAD_CLOSE_FAIL);
        }
    }

    @Override
    public TradingVo downLoadBill(TradingVo tradingVo) {
        //toDo 后面补齐
        throw  new RuntimeException("未支持：微信关下载账单!");
    }


}
